package org.boot.fast.util;

import org.boot.fast.properties.FastSystemProperties;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.boot.fast.core.api.mapper.provider.DynamicSqlProvider.SQL_KEYWORDS;
import static org.boot.fast.properties.FastSystemProperties.getProperties;
import static org.boot.fast.util.MappingUtil.mappingJoinIn;

public class SqlParamUtil {
    public static Map<String, Object> convertParamMap(Map<String, Object> params) {
        if (CollUtil.isEmpty(params)) {
            return params;
        }
        FastSystemProperties properties = getProperties();
        if (properties.getBatis().isCamelCase() && cn.hutool.core.collection.CollUtil.isNotEmpty(params)) {
            params = camelCaseMap(params);
        }
        return params;
    }

    public static List<Map<String, Object>> convertParamMap(List<Map<String, Object>> params) {
        if (CollUtil.isEmpty(params)) {
            return params;
        }
        FastSystemProperties properties = getProperties();
        if (properties.getBatis().isCamelCase() && cn.hutool.core.collection.CollUtil.isNotEmpty(params)) {
            params = params.stream().map(SqlParamUtil::camelCaseMap).collect(Collectors.toList());
        }
        return params;
    }

    private static Map<String, Object> camelCaseMap(Map<String, Object> map) {
        if (map == null) {
            return null;
        }
        Map<String, Object> result = new LinkedHashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (SQL_KEYWORDS.contains(entry.getKey())){
                result.put(entry.getKey(), entry.getValue());
                continue;
            }
            result.put(mappingJoinIn(entry.getKey()), entry.getValue());
        }
        return result;
    }
}
